var express = require('express');
const { aesDecrypt, checkUsername } = require('../utils');
const { UserModel, MvModel } = require('../utils/model');
var router = express.Router();

/* GET home page. */
//get get请求
//req 请求
//res 响应
//next 进入下一个中间件
//res.render 渲染页面  ejs
router.get('/', function (req, res, next) {
  res.render('index', {
    username: req.session.username,
    title: '电影后台管理系统',
  })
});

//send  发送文本 字符串
//json  发送json格式数据
//query  req.query
//：便是生命参数  凡是：声明的参数通过 params 来取值
//？ 允许为空

//all get&&post 既可以用get也可以用post请求
//req.body 获取 post 请求的参数

//登录
router.get('/login', (req, res) => {
  var username = req.query.username ? aesDecrypt(req.query.username) : '';
  var password = req.query.password ? aesDecrypt(req.query.password) : '';
  res.render('login', { username, password });
})

//注册
router.get("/register", (req, res) => {
  res.render("register")
})


//注销
router.get('/logout', (req, res) => {
  //销毁session
  req.session.destroy(() => {
    res.redirect('/');  // redirect 重定向
  })
})

//个人中心
router.get('/mine', (req, res) => {
  if (req.session.username) {
    UserModel.findOne({
      username: req.session.username
    }).then(result => {
      res.render('mine', {
        username: req.session.username,
        result
      })
    })
  } else {
    res.send(`<script>alert('你登录已经失效,请重新登录');location.href='/login'</script>`)
  }
})

//修改密码
router.post('/changepass', (req, res) => {
  var { oldpassword, newpassword } = req.body;
  if (req.session.username) {
    UserModel.findOne({
      username: req.session.username
    }).then(result => {
      if (result.password == oldpassword) {
        //修改
        UserModel.updateMany({
          username: req.session.username
        }, {
          $set: {
            password: newpassword
          }
        }).then(data => {
          res.json({
            code: 200,
            type: 1,
            msg: '密码修改成功，请登录验证！'
          })
        })
      } else {
        res.json({
          code: 200,
          type: 0,
          msg: '旧密码不正确，请输入正确的密码！'
        })
      }
    })
  } else {
    res.json({
      code: 3000,  // 3000 登录失败
      type: 0,
      msg: '你登录已经失效,请重新登录！'
    })
  }
})

//电影中心
router.get('/movie', (req, res) => {
  checkUsername(req, res, (username) => {
    //查询电影的数据
    var { year, score, index, def } = req.query;
    if (year) {
      MvModel.find({}, { _id: 0 }).sort({ year: index })
        .then(result => {
          res.json({
            result
          })
        })
    } else if (score) {
      MvModel.find({}, { _id: 0 }).sort({ 'rating.average': index })
        .then(result => {
          res.json({
            result
          })
        })
    } else if (def) {
      MvModel.find({}, { _id: 0 })
        .then(result => {
          res.json({
            result
          })
        })
    } else {
      MvModel.find({}, { _id: 0 })
        .then(result => {
          res.render('movie', {
            username,
            result
          })
        })
    }
  })
})


//电影详情
router.get('/mvDetail', (req, res) => {
  checkUsername(req, res, username => {
    var { mid } = req.query;
    MvModel.findOne({
      id: mid
    }).then(result => {
      res.render('detail', {
        username,
        result
      })
    })
  })
})

//电影搜索
router.get('/search', (req, res) => {
  checkUsername(req, res, username => {
    var { str } = req.query;
    MvModel.find({
      $or: [
        { title: new RegExp(str) },
        { genres: { $in: [str] } }
      ]
    }, { _id: 0 }).then(result => {
      console.log(result);
      if(result.length == 0){
        res.json({
          code:200,
          type:0,
          msg:'没有搜索到结果！'
        })
      }else{
        res.json({
          code:200,
          type:1,
          result
        })
      }
    })
  })
})

router.get('/client',(req,res)=>{
  checkUsername(req,res,username=>{
      res.render('client',{username})
  })
})




module.exports = router;
